/**菜单数据管理 */
import { defineStore } from "pinia"
import {
    addMenuList,
    getMenuList,
    editMenuList,
    delMenuList
} from "../api/menusApi.js"
import { ElMessage } from "element-plus";

const useMenuStore = defineStore("menus", {
    state: () => {
        return {
            menuList: []
        }
    },
    getters: {

    },
    actions: {
        GET_MENULIST(list) {
            this.menuList = list
        },
        // 获取菜单数据
        getMenuListActions() {
            getMenuList().then((res) => {
                console.log('菜单列表', res)
                if (res.code === 200) {
                    this.GET_MENULIST(res.list)
                }
            })
        },
        // 新增菜单
        addMenusListActions(menuList) {
            addMenuList(menuList).then((res) => {
                if (res.code === 200) {
                    // 重新获取数据
                    this.getMenuListActions();
                    ElMessage({
                        type: "success",
                        message: "新增菜单成功",
                    });
                } else {
                    ElMessage({
                        type: "error",
                        message: res.msg,
                    });
                }
            });
        },
        // 删除菜单
        delMenuListActions(id) {
            delMenuList(id).then((res) => {
                if (res.code === 200) {
                    // 重新获取数据
                    this.getMenuListActions();
                    ElMessage({
                        type: "success",
                        message: "删除菜单成功",
                    });
                } else {
                    ElMessage({
                        type: "error",
                        message: res.msg,
                    });
                }
            });
        },
        // 编辑菜单
        editMenuListActions(menuList) {
            // 调用api函数
            editMenuList(menuList).then((res) => {
                // console.log('编辑菜单的结果---------------------', res)
                if (res.code === 200) {
                    ElMessage({
                        type: "success",
                        message: "菜单更新成功了！"
                    })
                    // 重新请求菜单数据（调用其他action函数）
                    this.getMenuListActions()
                } else {
                    ElMessage({
                        type: "error",
                        message: res.msg
                    })
                }
            })
        },
    }
})
// 导出store
export default useMenuStore;